package com.weige.elefence.mq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author ltj
 * @Description 消费者消费消息
 * @date 2022/5/24
 */
public class Consumer {


    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        // 连接IP
        connectionFactory.setHost("192.168.1.21");
        // 连接端口
        connectionFactory.setPort(5672);
        // 虚拟主机(默认为/)
        connectionFactory.setVirtualHost("env");
        // 账号 默认是guest
        connectionFactory.setUsername("admin");
        // 密码 默认是guest
        connectionFactory.setPassword("admin");
        // 创建连接
        Connection connection = connectionFactory.newConnection();
        // 创建信道
        Channel channel = connection.createChannel();
        com.rabbitmq.client.Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, StandardCharsets.UTF_8);
                System.out.println("消息体为:" + msg);
                System.out.println("路由键为:" + envelope.getRoutingKey());
                System.out.println("交换机为:" + envelope.getExchange());
                System.out.println("标签为:" + envelope.getDeliveryTag());
                // 手动ACK,第二个参数是 是否批量处理
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        // 第一个参数是:订阅的队列名称,第二个参数是:是否自动确认消息,第三个参数是:消费者标签,
        // 第四个参数是:不支持的参数,第五个参数是:是否独占,第六个是:创建参数,第七个是:消费者
        channel.basicConsume("env_data", false, "", false, false, null, consumer);

    }

}
